package com.tadpole.music.view.activity.login;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import com.tadpole.music.R;
import com.tadpole.music.app.MyApplication;
import com.tadpole.music.bean.PushBean;
import com.tadpole.music.bean.WeChatUserInfoBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.login.LoginIView;
import com.tadpole.music.iView.wechat.UserInfoWeChatIView;
import com.tadpole.music.iView.wechat.WeChatBindPhone;
import com.tadpole.music.presenter.login.LoginPresenter;
import com.tadpole.music.presenter.wechat.UserInfoWeChatPresenter;
import com.tadpole.music.presenter.wechat.WeChatBindPhonePresenter;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.StatusBarUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.MainActivity;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.web.H5Activity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import cn.jpush.android.api.JPushInterface;

/**
 * 密码登录
 * Created By 孙岩
 * on 2020/9/7
 */
public class LoginActivity extends BaseActivity implements LoginIView, UserInfoWeChatIView, WeChatBindPhone {
    //手机号
    private EditText etPhone;
    //密码
    private EditText etPassword;
    //登录
    private TextView tvLogin;
    //忘记密码
    private TextView tvForget;
    //去注册
    private TextView tvGoRegister;
    //选中隐私政策
    private LinearLayout llSelect;
    //选中图标
    private ImageView ivSelect;
    //文字
    private TextView tv_notice;
    private boolean flag = false;
    //登录
    private LoginPresenter loginPresenter;
    //微信登录获取微信信息的presenter
    private UserInfoWeChatPresenter userInfoWeChatPresenter;
    //微信绑定手机号
    private WeChatBindPhonePresenter weChatBindPhonePresenter;
    //微信登录
    private ImageView ivLoginByWeChat;
    //极光id
    private String jPushId;
    //微信返回的数据源
    private WeChatUserInfoBean bean;
    //接收openId和access_token的广播
    private WxGetOpenidBroadcast mBroadcast;
    @SuppressLint("HandlerLeak")
    private  Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {//微信
                try {
                    String openId = msg.getData().getString("wxOpenid");
                    String access_token = msg.getData().getString("access_token");

                    SpUtil.getInstance(LoginActivity.this).putString(Constant.KEY_WX_OPENID,openId);
                    SpUtil.getInstance(LoginActivity.this).putString(Constant.ACCESS_TOKEN,access_token);

                    LoginActivity.this.userInfoWeChatPresenter.getUserInfo(openId, access_token);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //将头部状态栏置为透明
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        mBroadcast = new WxGetOpenidBroadcast();
        registerReceiver(mBroadcast, new IntentFilter(Constant.BIND_WX_GET_OPENID));
        initViews();
        initListeners();

        //获取jPushId
        jPushId = JPushInterface.getRegistrationID(getApplicationContext());

        //获取微信用户信息
        userInfoWeChatPresenter = new UserInfoWeChatPresenter();
        userInfoWeChatPresenter.attachView(this);
        //登录
        loginPresenter = new LoginPresenter();
        loginPresenter.attachView(this);

        //查询时候绑定手机号
        weChatBindPhonePresenter = new WeChatBindPhonePresenter();
        weChatBindPhonePresenter.attachView(this);
    }

    //初始化控件
    private void initViews() {
        etPhone = findViewById(R.id.etPhone);
        etPassword = findViewById(R.id.etPassword);
        tvLogin = findViewById(R.id.tvLogin);
        tvForget = findViewById(R.id.tvForget);
        tvGoRegister = findViewById(R.id.tvGoRegister);
        ivLoginByWeChat = findViewById(R.id.ivLoginByWeChat);
        llSelect = findViewById(R.id.llSelect);
        ivSelect = findViewById(R.id.ivSelect);
        tv_notice = findViewById(R.id.tv_notice);

        SpannableString spannable = new SpannableString ("已阅读并同意蝌蚪音基《隐私政策》 ");

        //这个一定要记得设置，不然点击不生效
        tv_notice.setMovementMethod(LinkMovementMethod.getInstance());
        tv_notice.setHighlightColor(Color.TRANSPARENT);
        //用户协议
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                if(Mutils.isNetworkAvailable()){
                    PushBean pushBean = new PushBean();
                    pushBean.setUrl("https://kedou.aiyuechen.com/api/v2/notice/81");
                    pushBean.setTitle("隐私政策");
                    Intent intent = new Intent(LoginActivity.this, H5Activity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("params",pushBean);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setLinearText(false);
            }
        }, 10, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的前景色
        spannable.setSpan(getRedSpan(),10,16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_notice.setText(spannable);
    }

    private ForegroundColorSpan getRedSpan(){
        return new ForegroundColorSpan(ContextCompat.getColor(this,R.color.colorMain));
    }


    //初始化监听器
    private void initListeners() {
        //去注册
        tvGoRegister.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    Intent intent = new Intent(LoginActivity.this, SelectIdentityActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //忘记密码
        tvForget.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    Intent intent = new Intent(LoginActivity.this, RetrievePwdActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        llSelect.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(flag){
                    ivSelect.setImageResource(R.mipmap.weixuan);
                    flag = false;
                }else{
                    ivSelect.setImageResource(R.mipmap.yixuan);
                    flag = true;
                }
            }
        });

        //微信登录
        ivLoginByWeChat.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if(!flag){
                        ToastUtils.show("请先同意隐私政策");
                    }else {
                        if(MyApplication.mWxApi!=null){
                            if (!MyApplication.mWxApi.isWXAppInstalled()) {
                                ToastUtils.show("您还没有安装微信客户端");
                                return;
                            }
                        }

                        SendAuth.Req req = new SendAuth.Req();
                        req.scope = "snsapi_userinfo";//获取用户个人信息
                        req.state = "1";
                        MyApplication.mWxApi.sendReq(req);
                    }
                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //提交
        tvLogin.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if(!flag){
                        ToastUtils.show("请先同意隐私政策");
                    }else{
                        if (etPhone.getText().toString().trim().equals("")) {
                            ToastUtils.show("请输入手机号");
                        } else if (etPassword.getText().toString().trim().equals("")) {
                            ToastUtils.show("请输入密码");
                        } else {
                            loginPresenter.login(etPhone.getText().toString().trim(), etPassword.getText().toString().trim(),jPushId);
                        }
                    }


                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void showLoginResult(String token) {
        ToastUtils.show("登录成功");
        SpUtil.getInstance(this).putString(Constant.TOKEN, "Bearer "+ token);

        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    //微信登录，我拿上微信给我返回的东西，我叼你的接口api/v2/wxlogin
    @Override
    public void showUserInfo(WeChatUserInfoBean bean) {
        this.bean = bean;
        weChatBindPhonePresenter.bindPhone(
                bean.getOpenid(),
                bean.getUnionid(),
                bean.getNickname(),
                bean.getCountry(),
                bean.getLanguage(),
                bean.getProvince(),
                bean.getCity(),
                bean.getHeadimgurl(),
                bean.getSex(),
                jPushId,
                "",
                ""
        );
    }

    //微信已经绑定手机 直接登录
    @Override
    public void showToken(String token) {
        ToastUtils.show("登录成功");
        SpUtil.getInstance(this).putString(Constant.TOKEN, "Bearer "+ token);

        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }


    //微信未绑定手机，去绑定
    @Override
    public void bindPhone() {
        Intent intent = new Intent(LoginActivity.this,BindPhoneActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("info",bean);
        bundle.putString("jPushId",jPushId);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 微信登录返回用户信息的广播
     */
    public class WxGetOpenidBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            String wxOpenid = intent.getExtras().getString(Constant.KEY_WX_OPENID);
            String access_token = intent.getExtras().getString(Constant.ACCESS_TOKEN);
            Message msg = Message.obtain();
            msg.what = 1;
            Bundle bundle = new Bundle();
            bundle.putString("wxOpenid",wxOpenid);
            bundle.putString("access_token",access_token);
            msg.setData(bundle);
            mHandler.sendMessage(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mBroadcast!=null){
            unregisterReceiver(mBroadcast);
            mBroadcast = null;
        }
    }
}
